﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Devices;
using com.google.zxing.qrcode;
using ScannerDemo;
using com.google.zxing.common;
using com.google.zxing;
using System.Windows.Threading;

namespace WP7.QR.Views
{
    public partial class QRReaderPage : PhoneApplicationPage
    {
        private PhotoCamera photoCamera;
        private QRCodeReader codeReader;
        private DispatcherTimer dispatcherTimer = new DispatcherTimer();

        public QRReaderPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            photoCamera = new PhotoCamera(CameraType.Primary);
            photoCamera.Initialized += (s, a) =>
            {
                codeReader = new QRCodeReader();
                Dispatcher.BeginInvoke(() => { compositeTransform.Rotation = photoCamera.Orientation; });
            };
            videoBrush.SetSource(photoCamera);

            dispatcherTimer.Interval = TimeSpan.FromMilliseconds(250);
            dispatcherTimer.Tick += (o, arg) => ScanPreviewBuffer();
            dispatcherTimer.Start();
            base.OnNavigatedTo(e);
        }

        private void ScanPreviewBuffer()
        {
            try
            {
                int width = Convert.ToInt32(photoCamera.PreviewResolution.Width);
                int height = Convert.ToInt32(photoCamera.PreviewResolution.Height);
                PhotoCameraLuminanceSource _luminance = new PhotoCameraLuminanceSource(width, height);
                photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);

                var binBitmap = new BinaryBitmap(new HybridBinarizer(_luminance));
                var result = codeReader.decode(binBitmap);
                NavigationService.Navigate(new Uri(string.Format("/Views/QRReaderResultPage.xaml?qrcode={0}", result.Text), UriKind.RelativeOrAbsolute));

            }
            catch { }
        }
    }
}